package sk.mka.phd.googleagent.query;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import org.apache.log4j.Logger;
import org.json.JSONObject;

/**
 *
 * @author bracek
 * @date Aug 2, 2010
 */
public class AjaxGoogleQuery extends AbstractGoogleQuery implements IGoogleQuery {

    private String endpointURL = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&key=" + MY_PRIVATE_GOOGLE_KEY + "&q=";
    private static final Logger log = Logger.getLogger(AjaxGoogleQuery.class);

    @Override
    public String makeQuery(String word) {

        String results = null;
        try {
            word = word.replace(" ", "+");
            log.warn(word);
            String endpointQuery = endpointURL + word;
//            log.warn(endpointQuery);
            URLConnection uc = new URL(endpointQuery).openConnection();
            uc.setRequestProperty("User-Agent", REQUEST_VALUE);

            HttpURLConnection connection = (HttpURLConnection) uc;
            connection.setDoOutput(true);
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(200000);
            connection.connect();
            String line;
            InputStream inputStream = null;
            inputStream = connection.getInputStream();
            StringBuilder builder = new StringBuilder();
            BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = rd.readLine()) != null) {
                builder.append(line);
            }
            String response = builder.toString();
            JSONObject json = new JSONObject(response);
            results = json.getJSONObject("responseData").getJSONObject("cursor").getString("estimatedResultCount");
            inputStream.close();
        } catch (Exception ex) {
            log.error(ex + word);
        }

        return results;
    }
}
